package spaceshop

import (
	"errors"

	"log"

	"github.com/astaxie/beego/orm"
)

func init() {
	orm.RegisterModel(new(User))
}

type User struct {
	ID       string  `json:"id" orm:"pk;column(ID)"`
	Email    string  `json:"email"`
	UserName string  `json:"username"`
	Password string  `json:"-"`
	Profile  Profile `orm:"-"`
}

func (t *User) TableName() string {
	return "admin_user"
}

type Profile struct {
	Gender  string
	Age     int
	Address string
	Email   string
}

func AddUser(u User) int {
	o := orm.NewOrm()
	id, _ := o.Insert(&u)
	return int(id)
}

func GetUser(uid string) (u *User, err error) {
	uid = "todo"
	return nil, errors.New("User not exists")
}

func GetAllUsers() []*User {
	var us []*User
	o := orm.NewOrm()
	o.QueryTable("admin_user").All(&us)
	return us
}

func UpdateUser(uid string, uu *User) (a *User, err error) {
	o := orm.NewOrm()
	u := User{ID: uid}
	if err := o.Read(&u); err == nil {
		if uu.UserName != "" {
			u.UserName = uu.UserName
		}
		if uu.Password != "" {
			u.Password = uu.Password
		}
		if uu.Profile.Age != 0 {
			u.Profile.Age = uu.Profile.Age
		}
		if uu.Profile.Address != "" {
			u.Profile.Address = uu.Profile.Address
		}
		if uu.Profile.Gender != "" {
			u.Profile.Gender = uu.Profile.Gender
		}
		if uu.Profile.Email != "" {
			u.Profile.Email = uu.Profile.Email
		}
		return &u, nil
	}
	return nil, errors.New("User Not Exist")
}

func Login(email, password string) *User {
	sU := User{}
	o := orm.NewOrm()
	if err := o.QueryTable(`admin_user`).SetCond(orm.NewCondition().And("Email", email).And("Password", password)).One(&sU); err == nil {
		return &sU
	} else {
		log.Print(err)
	}

	return nil
}

func DeleteUser(uid string) {
	o := orm.NewOrm()
	o.Delete(&User{ID: uid})
}
